﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace DotNetExtensions.AspNet.Converters
{
    public class JsonTypeConverter : JsonConverter<Type>
    {
        public override bool CanRead => true;
        public override bool CanWrite => true;

        public override Type ReadJson(JsonReader reader, Type objectType, Type existingValue, bool hasExistingValue, JsonSerializer serializer)
        {

            if (reader.TokenType == JsonToken.Null)
            {
                return null;
            }
            else
            {
                string json = reader.Value.ToString();

                if (string.IsNullOrEmpty(json) || json.LastIndexOf("Module") == -1) return null;

                TypeValue value = JsonConvert.DeserializeObject<TypeValue>(json);

                if (value == null) return null;

                return null;//ExpressionResolver.TryGetType(value.Module, value.Clazz);
            }
        }

        public override void WriteJson(JsonWriter writer, Type value, JsonSerializer serializer)
        {
            if (value == null)
            {
                writer.WriteNull();
            }
            else
            {
                Type type = value as Type;

                if (type == null)
                {
                    throw new ArgumentException($"{value.GetType().FullName} is not an valid [Type] value.");
                }
                TypeValue typeValue = new TypeValue();
                typeValue.Clazz = type.FullName;
                typeValue.Module = type.Module.Name;

                string data = JsonConvert.SerializeObject(typeValue);
                writer.WriteValue(data);
            }
        }
    }
}
